package androidtool.abdwireless;

import androidtool.MainMenu;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Hoang
 */
public class ADBMainGUI extends javax.swing.JFrame {

    private MainMenu mainMenu;
    private String dirAndroidSDK;
    private String dirFolderADBWirelessSetting = "C:\\Users\\Hoang\\.android";
    private String dirADBWirelessSetting = dirFolderADBWirelessSetting + "\\ADBWirelessSetting.txt";

    /**
     * Creates new form ADBMainGUI
     */
    public ADBMainGUI(MainMenu mainMenu) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
        }

        this.mainMenu = mainMenu;

        initComponents();
        setVisible(true);
        setLocation(200, 100);
        if (!checkSetting()) {
            JOptionPane.showMessageDialog(null, "Choose folder android-sdk for first using!");
            chooseFolder();

            File file = new File(dirADBWirelessSetting);
            try {
                Writer output = new BufferedWriter(new FileWriter(file));
                output.write(dirAndroidSDK);
                output.close();
            } catch (IOException ex) {
                Logger.getLogger(ADBMainGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        String myIP = getMyIP();
        String subIP = "";
        int temp = 0;
        for (int i = 0; i < myIP.length(); i++) {
            if (temp < 3) {
                subIP += myIP.charAt(i);
                if (myIP.charAt(i) == '.') {
                    temp++;
                }
            }
        }
        lblHeaderIp.setText(subIP);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtFooterIp = new javax.swing.JTextField();
        lblHeaderIp = new javax.swing.JLabel();
        btnKillServer = new javax.swing.JButton();
        btnDisconnect = new javax.swing.JButton();
        txtPacket = new javax.swing.JTextField();
        btnUninstall = new javax.swing.JButton();
        btnConnect = new javax.swing.JButton();
        btnStartServer = new javax.swing.JButton();
        btnDevice = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtNotice = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ADB Wireless");

        txtFooterIp.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtFooterIp.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFooterIp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtFooterIpActionPerformed(evt);
            }
        });
        txtFooterIp.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtFooterIpKeyPressed(evt);
            }
        });

        lblHeaderIp.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblHeaderIp.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblHeaderIp.setText("192.168.1.");
        lblHeaderIp.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnKillServer.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnKillServer.setText("Kill server");
        btnKillServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnKillServerActionPerformed(evt);
            }
        });

        btnDisconnect.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnDisconnect.setText("Disconnect");
        btnDisconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDisconnectActionPerformed(evt);
            }
        });

        txtPacket.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtPacket.setText("com.");
        txtPacket.setBorder(javax.swing.BorderFactory.createTitledBorder("Packet"));

        btnUninstall.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnUninstall.setText("Uninstall");
        btnUninstall.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUninstallActionPerformed(evt);
            }
        });

        btnConnect.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnConnect.setText("Connect");
        btnConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnectActionPerformed(evt);
            }
        });

        btnStartServer.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnStartServer.setText("Start server");
        btnStartServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartServerActionPerformed(evt);
            }
        });

        btnDevice.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnDevice.setText("Device");
        btnDevice.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeviceActionPerformed(evt);
            }
        });

        txtNotice.setColumns(20);
        txtNotice.setRows(5);
        jScrollPane1.setViewportView(txtNotice);

        jMenu1.setText("File");

        jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem4.setText("Open Main menu");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem4);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Creat android-sdk directory ");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText("Quit");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Help");

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        jMenuItem3.setText("About");
        jMenu2.add(jMenuItem3);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblHeaderIp, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtFooterIp, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnDevice, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnConnect, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnDisconnect, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnStartServer, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnKillServer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(txtPacket, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnUninstall, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(txtFooterIp, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                    .addComponent(lblHeaderIp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnDisconnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnConnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnStartServer, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                    .addComponent(btnKillServer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnDevice, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPacket, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnUninstall, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        chooseFolder();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void txtFooterIpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFooterIpActionPerformed
    }//GEN-LAST:event_txtFooterIpActionPerformed

    private void btnKillServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKillServerActionPerformed
        String command = "kill-server";
        String s = excuteCommand(command);
        if (s.equals("")) {
            txtNotice.setText("Kill server success!");
        } else {
            txtNotice.setText("Kill server error!");
        }
    }//GEN-LAST:event_btnKillServerActionPerformed

    private void btnDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDisconnectActionPerformed
        String command = "disconnect " + lblHeaderIp.getText() + txtFooterIp.getText();
        txtNotice.setText(excuteCommand(command));
    }//GEN-LAST:event_btnDisconnectActionPerformed

    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed
        String command = "connect " + lblHeaderIp.getText() + txtFooterIp.getText();
        txtNotice.setText(excuteCommand(command));
    }//GEN-LAST:event_btnConnectActionPerformed

    private void btnStartServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartServerActionPerformed
        String command = "start-server";
        String s = excuteCommand(command);
        if (s.equals("")) {
            txtNotice.setText("Start server success!");
        } else {
            txtNotice.setText("Start server error!");
        }
    }//GEN-LAST:event_btnStartServerActionPerformed

    private void btnUninstallActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUninstallActionPerformed
        String command = "uninstall " + txtPacket.getText();
        txtNotice.setText(excuteCommand(command));
    }//GEN-LAST:event_btnUninstallActionPerformed

    private void btnDeviceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeviceActionPerformed
        String command = "devices";
        txtNotice.setText(excuteCommand(command));
    }//GEN-LAST:event_btnDeviceActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        if (mainMenu == null) {
            mainMenu = new MainMenu();
        }
        mainMenu.setVisible(true);
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void txtFooterIpKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFooterIpKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) { 
            String command = "connect " + lblHeaderIp.getText() + txtFooterIp.getText();
            txtNotice.setText(excuteCommand(command));
        }
    }//GEN-LAST:event_txtFooterIpKeyPressed

    private String excuteCommand(String command) {
        String s = "";
        try {
            String cm = dirAndroidSDK + "\\platform-tools\\adb.exe " + command;
            System.out.println(cm);
            Process p = Runtime.getRuntime().exec(cm);
            try (InputStream in = p.getInputStream()) {
                int c;

                while ((c = in.read()) != -1) {
                    s += (char) c;
                }
                System.out.println("s: " + s);
                //                jLabel3.setText(s);
            }
            p.destroy();
        } catch (IOException ex) {
            Logger.getLogger(ADBMainGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        return s;
    }

    private void chooseFolder() {
        final JFileChooser fc = new JFileChooser();
        JList list = new JList();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
            File file = fc.getSelectedFile();
            dirAndroidSDK = file.getPath();
            JOptionPane.showMessageDialog(null, "New android-sdk's directory is: " + dirAndroidSDK);
            txtNotice.setText(dirAndroidSDK);
        }
    }

    private boolean checkSetting() {

        String files;
        File folder = new File(dirFolderADBWirelessSetting);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                files = listOfFiles[i].getName();
                System.out.println(files);
                if (files.equalsIgnoreCase("ADBWirelessSetting.txt")) {

                    FileInputStream fstream = null;
                    try {
                        fstream = new FileInputStream(dirADBWirelessSetting);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(ADBMainGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    DataInputStream in = new DataInputStream(fstream);
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));

                    try {
                        dirAndroidSDK = br.readLine();
                        System.out.println(dirAndroidSDK);
                        in.close();
                    } catch (IOException ex) {
                        Logger.getLogger(ADBMainGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    txtNotice.setText(dirAndroidSDK);
                    return true;
                }
            }
        }
        return false;
    }

    private String getMyIP() {
        try {
            InetAddress ownIP = InetAddress.getLocalHost();
            return ownIP.getHostAddress();
        } catch (UnknownHostException ex) {
            return "";
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConnect;
    private javax.swing.JButton btnDevice;
    private javax.swing.JButton btnDisconnect;
    private javax.swing.JButton btnKillServer;
    private javax.swing.JButton btnStartServer;
    private javax.swing.JButton btnUninstall;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblHeaderIp;
    private javax.swing.JTextField txtFooterIp;
    private javax.swing.JTextArea txtNotice;
    private javax.swing.JTextField txtPacket;
    // End of variables declaration//GEN-END:variables
}
